//
//  MJTComposeView.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/18.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
import pop


class MJTComposeView: UIView {
    //  记录在哪个控制器上弹出
    private var target: UIViewController?
    //  记录6个撰写按钮
    private lazy var composeButtonArray = [MJTComposeMenuButton]()
    //MARK: 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenImage().applyLightEffect())

    private lazy var cancelButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_background_icon_close"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "timeline_retweet_background_highlighted"), forState: .Normal)
        button.addTarget(self, action: "cancelAction", forControlEvents: .TouchUpInside)
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件,设置约束
    private func setupUI() {
        backgroundColor = RandomColor()
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        addSubview(bgImageView)
        addSubview(cancelButton)
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        cancelButton.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
            make.height.equalTo(35)
        }
        addChildButton()
    }
    //添加button
    private func addChildButton() {
        //宽度
        let buttonWidth: CGFloat = 80
        //高度
        let buttonHeight: CGFloat = 110
        //按钮之间的间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        //获取plist里面的数据
        let composeMenuArray = loadComposePlist()
        for (i, value) in composeMenuArray.enumerate() {
            let button = MJTComposeMenuButton()
            button.addTarget(self, action: "composeButtonAction:", forControlEvents: .TouchUpInside)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            // 计算列索引
            let colIndex = i % 3
            // 行索引
            let rowIndex = i / 3
            // 计算x坐标
            button.x = buttonWidth * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            // 计算y坐标
            button.y = buttonHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin   + ScreenHeight
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            addSubview(button)
            //记录按钮
            composeButtonArray.append(button)
        }
    }
    //读取plist文件
    private func loadComposePlist() -> [MJTComposeMenu] {
        //获取plist路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //读取plist
        let composeDicArray = NSArray(contentsOfFile: path)!
        var tempArray = [MJTComposeMenu]()
        for dic in composeDicArray {
            let composeMenu = MJTComposeMenu(dic: dic as! [String: AnyObject])
            tempArray.append(composeMenu)
        }
        return tempArray
    }

    func show(target: UIViewController){
        self.target = target
        //  获取最上面的一个window
        //        let window = UIApplication.sharedApplication().windows.last!
        //        window.addSubview(self)
        target.view.addSubview(self)
        //  开启动画
        for (i, value) in composeButtonArray.enumerate() {
            startAnimation(value, i: i, isUP: true)
        }
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //  开启动画
        for (i, value) in composeButtonArray.reverse().enumerate() {

            startAnimation(value, i: i, isUP: false)

        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //  结束刷新
            self.removeFromSuperview()
        })

    }
    @objc private func cancelAction() {
        //  开启动画
        for (i, value) in composeButtonArray.reverse().enumerate() {
            startAnimation(value, i: i, isUP: false)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //  结束刷新
            self.removeFromSuperview()
        })
    }
    //  开启动画
    private func startAnimation(value: MJTComposeMenuButton, i: Int, isUP: Bool) {
        //  改变视图中心点的弹簧动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)

        let y = isUP ? value.centerY - 350 : value.centerY + 350

        //  动画目的地
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        //  弹簧弹力
        animation.springBounciness = 8
        //  弹簧速度
        animation.springSpeed = 10
        //  一个一个弹出
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        //  执行动画
        value.pop_addAnimation(animation, forKey: nil)
    }
    // MARK:    --点击事件
    @objc private func composeButtonAction(btn: MJTComposeMenuButton) {
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.composeButtonArray {
                value.alpha = 0.2
                if value == btn {
                    //  放大
                    value.transform = CGAffineTransformMakeScale(3, 3)
                } else {
                    //  缩小
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) -> Void in
                //  动画执行完成在重置原始样子
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    for value in self.composeButtonArray {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                        //  弹出控制器，移除当前视图
                        self.showComposeVC()
                })
        }
    }
    private func showComposeVC() {
        let composeVC = MJTComposeViewController()
        let composeNav = UINavigationController(rootViewController: composeVC)
        self.target?.presentViewController(composeNav, animated: true, completion: { () -> Void in
            self.removeFromSuperview()
        })
    }
}